import ast
import re

from django.http import JsonResponse
from pymysql import DatabaseError
from rest_framework.response import Response
from rest_framework_jwt.settings import api_settings
from rest_framework.views import APIView

from apps.classapi.models import Class
from apps.user.models import User
from apps.user.serializers.user import UserSerializer
from apps.user.utils.user import OpenidUtils
from utils.bases64 import main


class UserLogin(APIView):
    # 获取授权信息
    def get(self, request):
        users = request.GET.get("js_code")
        open_id = OpenidUtils.get_openid(users, users)
        print(open_id)
        try:
            user = User.objects.get(open_id=open_id)
        except Exception as e:
            user = None

        if user:
            # 更新用户信息
            user = User.objects.get(open_id=open_id)
            jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
            jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER

            payload = jwt_payload_handler(user)
            token = jwt_encode_handler(payload)
            ret = {'code': '00000', 'msg': '授权成功', 'data': {
                'token': token,
                'uid': user.id,
                'uname': user.username,
                'op': open_id

            }}
        else:

            ret = {'code': '00000', 'msg': '授权失败', 'data': {
                'uid': 0,
                'op': open_id

            }}

        return JsonResponse(ret)


class UserBind(APIView):
    """用户绑定"""

    def get(self, request):
        username = request.GET.get("username")
        password = request.GET.get("password")
        open_id = request.GET.get("js_code")
        print(password, username, open_id)
        user = User.objects.filter(username=username).first()
        print(user)
        if not user:
            ret = {'uid': 0, "uname": "用户不存在"}
            return JsonResponse(ret)
        datas = {"open_id": open_id}
        print(user.check_password(password))
        if not user.check_password(password):
            ret = {'uid': 0, "uname": "账号或者密码错误"}
            return JsonResponse(ret)
        try:
            user.open_id = open_id
            user.save()
            jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
            jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER
            payload = jwt_payload_handler(user)
            token = jwt_encode_handler(payload)
        except User.DoesNotExist:
            ret = {'uid': 0, "uname": "绑定失败"}
            return JsonResponse(ret)
        ret = {'code': '00000', 'msg': '授权成功', 'data': {
            'token': token,
            'uid': user.id,
            'uname': user.username,
            'op': user.open_id
        }}
        return Response(ret)


class UserRegist(APIView):
    # 注册
    # 指定视图所使用的序列化器类
    serializer_class = UserSerializer

    def post(self, request):
        # 获取数据
        openid = request.POST.get("js_code")
        city = request.POST.get("city")
        avatarUrl = request.POST.get("avatarUrl")
        country = request.POST.get("country")
        language = request.POST.get("language")
        province = request.POST.get("province")
        gender = request.POST.get("gender")
        print("1231", gender)
        print(city)
        email = request.POST.get("regist_email")
        password = request.POST.get("regist_password")
        username = request.POST.get("regist_username")
        # 对数据进行检验
        if not all([username, password, email]):
            ret = {'code': '00003', 'msg': '缺少数据', 'data': {
                'uid': 0
            }}
            return JsonResponse(ret)
        print("15236", openid, email, password, username)
        if not re.match(r'^[0-9a-zA-Z_]{0,19}@[0-9a-zA-Z]{1,13}\.[com,cn,net]{1,3}$', email):
            ret = {'code': '00001', 'msg': '邮箱格式错误', 'data': {
                'uid': 0,
            }}
            return JsonResponse(ret)
        # 保存数据
        try:
            user = User.objects.create_user(username=username, password=password, email=email, open_id=openid,
                                            city=city, language=language, avatarUrl=avatarUrl, country=country,
                                            province=province, gender=gender)
            aclass = Class.objects.create(name="默认", user=user)
            jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
            jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER

            payload = jwt_payload_handler(user)
            token = jwt_encode_handler(payload)
        except DatabaseError:
            ret = {'code': '00002', 'msg': '注册失败', 'data': {
                'uid': 0,
            }}
            return JsonResponse(ret)

        ret = {'code': '00000', 'msg': '注册成功111', 'uid': user.id, 'token': token, 'user': {
            'uid': user.id,
            'uname': user.username

        }}
        return JsonResponse(ret)


class ApiUser(APIView):
    def get(self, request):
        uid = request.GET.get("uid")
        token = request.META.get("HTTP_TOKEN")
        jwt_decode_handler = api_settings.JWT_DECODE_HANDLER
        user_dict = jwt_decode_handler(token)
        user_id = user_dict['user_id']
        print(user_id)
        print(uid)
        try:
            user = User.objects.get(id=user_id)
        except Exception as e:
            ret = {'uid': 0, 'msg': '获取失败'}
            return JsonResponse(ret)
        ret = {'uid': uid, "username": user.username, "email": user.email}
        return JsonResponse(ret)

    def post(self, request):
        data = request.POST.get("data")
        types = request.POST.get("type")
        data1 = main(data)  # 将接受到的base64格式代码转化成python
        datas = ast.literal_eval(data1)  # 将接受到的数据转化成json格式
        user = User.objects.get(id=datas["uid"])
        if types == "updataPassword":
            """修改密码"""
            # 检查原始密码是否正确
            if not user.check_password(datas["old"]):
                ret = {
                    "uid": 0,
                    "username": "验证密码失败，请重新输入登录密码！"
                }
                return Response(ret)
            # 修改密码为新密码
            try:
                user.set_password(datas["new"])
                user.save()
            except Exception as e:
                ret = {"uid": 0,
                       "username": "密码修改失败，请重新输入登录密码！"}
                return Response(ret)
            ret = {"uid": user.id,
                   "username": user.username}
            return Response(ret)
        elif types == "updataUsername":
            """修改用户名"""
            # 检查原始密码是否正确
            if not user.check_password(datas["password"]):
                ret = {
                    "uid": 0,
                    "username": "验证密码失败，请重新输入登录密码！"
                }
                return Response(ret)
            # 保存新的用户名
            try:
                user.username = datas["username"]
                user.save()
            except Exception as e:
                ret = {"uid": 0,
                       "username": "用户名修改失败，请重新输入！"}
                return Response(ret)
            ret = {"uid": user.id,
                   "username": user.username}
            return Response(ret)


class Login(APIView):
    # 登录
    def get(self, request):
        username = request.GET.get("username")
        password = request.GET.get("password")
        print(username, password)
        user = User.objects.filter(username=username)
        if not user:
            ret = {'uid': 0, "uname": "用户不存在"}
            return JsonResponse(ret)

        print(user[0].password)
        if not user[0].check_password(password):
            ret = {'uid': 0, "uname": "账号或者密码错误"}
            return JsonResponse(ret)
        if user:
            # 更新用户信息
            user = User.objects.get(username=username)
            jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
            jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER

            payload = jwt_payload_handler(user)
            token = jwt_encode_handler(payload)
            ret = {'code': '00000', 'msg': '授权成功', 'data': {
                'token': token,
                'uid': user.id,
                'uname': user.username,
                'op': user.open_id

            }}
        else:

            ret = {'code': '00000', 'msg': '授权失败', 'data': {
                'uid': 0,
                'op': user.open_id

            }}

        return JsonResponse(ret)
